package com.lq.utils;

import com.lq.utils.jdbc.Jdbc;
import org.apache.log4j.Logger;

import java.lang.reflect.Field;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.LinkedHashMap;

public class CommonUtil {

    public static Logger log = Logger.getLogger(CommonUtil.class);

    public static String e(Exception e) {
        try {
            String str = e.toString() + "\r\n";
            for (int i = 0; i < e.getStackTrace().length; i++) {
                str += e.getStackTrace()[i] + "\r\n";
            }
            return str;
        } catch (Exception e1) {
            return "logerror";
        }
    }


    /**
     * 获取IP
     *
     * @return
     */
    public static String getRequestIP() {
        String ip = "";
        try {
            InetAddress address = InetAddress.getLocalHost();
            ip = address.getHostAddress();
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        }
        return ip;
    }


    /**
     * 实体类转换成Map
     *
     * @param obj
     * @return
     * @throws Exception
     */
    public static LinkedHashMap<String, String> objectToMap(Object obj) throws Exception {
        if (obj == null) {
            return null;
        }
        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        Field[] declaredFields = obj.getClass().getDeclaredFields();
        for (Field field : declaredFields) {
            field.setAccessible(true);
            map.put(field.getName(), field.get(obj).toString());
        }
        return map;
    }


    /**
     * 比较两个数组的值是否相同
     * @param arr1
     * @param arr2
     * @return 不一样返回false  一样返回true
     */
    public static boolean compare(String[] arr1, String[] arr2) {
        if (arr1.length == arr2.length) {
            for (int i = 0; i < arr1.length; i++) {
                if (!arr1[i].equals(arr2[i])) {
                    return false;
                }
            }
            return true;
        } else {
            return false;
        }
    }


    /**
     * 获取数据库连接
     */
    public static void getDBConnection() {
        long num_connections = 0;//总链接数
        long num_busy_connections = 0;//正在运行状态的连接数
        long num_idle_connections = 0;//空闲连接数
        try {
            num_connections = Jdbc.getNumConnectionsDefaultUser();
            num_busy_connections = Jdbc.getNumBusyConnectionsDefaultUser();
            num_idle_connections = Jdbc.getNumIdleConnectionsDefaultUser();
            log.info("数据库当前总连接数："+num_connections);
            log.info("数据库当前正常运行连接数："+num_busy_connections);
            log.info("数据库当前空闲连接数："+num_idle_connections);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}
